package photobox.manage

import grails.transaction.Transactional
import grails.validation.ValidationException
import photobox.exception.NotFoundException
import photobox.utils.HQLUtils
import photobox.utils.PermUtils
import photobox.photo.PhotoSize

@Transactional
class PhotoSizeService {

    def listPhotoSize(searchParam, pageParam, sortParam) {
        def hql = ""
        hql += " from PhotoSize A where 1=1 "
        def params = [:]
        if (searchParam.id) {
            hql += " and " + HQLUtils.whereCondition("A.id", searchParam.id.opt, "id")
            params.id = searchParam.id.data
        }
        if (searchParam.width) {
            hql += " and " + HQLUtils.whereCondition("A.width", searchParam.width.opt, "width")
            params.width = searchParam.width.data
        }
        if (searchParam.height) {
            hql += " and " + HQLUtils.whereCondition("A.height", searchParam.height.opt, "height")
            params.height = searchParam.height.data
        }
        if (searchParam.packingPrice) {
            hql += " and " + HQLUtils.whereCondition("A.packingPrice", searchParam.packingPrice.opt, "packingPrice")
            params.packingPrice = searchParam.packingPrice.data
        }
        def sortHql = ""
        if (sortParam.sort) {
            sortHql = " order by A.${sortParam.sort} ${sortParam.order} "
        }
        def results = PhotoSize.executeQuery("select distinct A " + hql + sortHql, params,
                [max: pageParam.pageSize, offset: pageParam.offset])
        def count = PhotoSize.executeQuery("select count(distinct A.id) " + hql, params)
        return [rs:results, total:count[0]]
    }
    def createPhotoSize(params) {
        PhotoSize photoSize = new PhotoSize()
        photoSize.width  = params.int('width')
        photoSize.height = params.int('height')
        if(!params.packingPrice){
            throw new NotFoundException("包装费不能为空")
        }
        photoSize.packingPrice = params.float('packingPrice')
        if (!photoSize.save()) {
            throw new ValidationException("创建图片尺寸时发生错误", photoSize.errors)
        }
    }
    def updatePhotoSize(params) {
        def photoSize = PhotoSize.get(params.id as Long)
        if (!photoSize) {
            throw new NotFoundException("没有找到对应的图片尺寸")
        }
        photoSize.width  = params.int('width')
        photoSize.height = params.int('height')
        photoSize.packingPrice = params.float('packingPrice')
        if (!photoSize.save()) {
            throw new ValidationException("创建图片尺寸时发生错误", photoSize.errors)
        }
    }

    def deletePhotoSize(params) {
        def photoSize = PhotoSize.get(params.id as Long)
        if (!photoSize) {
            throw new NotFoundException("没有找到对应的图片尺寸")
        }
        photoSize.delete()
    }
}
